use std::path::PathBuf;

use axum::{
    body::Body,
    http::{header, StatusCode},
    response::{IntoResponse, Response},
    routing, Router,
};
use tokio::fs::File;
use tokio_util::io::ReaderStream;

pub struct DownloadHandler {
    routes: Router,
}

impl Into<Router> for DownloadHandler {
    fn into(self) -> Router {
        self.routes
    }
}

impl DownloadHandler {
    pub fn init() -> Self {
        let routes = Router::new().route("/package", routing::get(download_netfiler));

        Self { routes }
    }
}

async fn download_netfiler() -> Result<impl IntoResponse, StatusCode> {
    let netfilter_file_path = PathBuf::from("./netfilter.zip");
    if !netfilter_file_path.exists() {
        return Err(StatusCode::NOT_FOUND);
    }
    let file = File::open(netfilter_file_path).await.unwrap();
    let stream = ReaderStream::new(file);
    let body = Body::from_stream(stream);
    let response = Response::new(body);
    Ok((
        StatusCode::OK,
        [(
            header::CONTENT_DISPOSITION,
            "attachment; filename=netfilter.zip",
        )],
        response,
    ))
}
